package com.ssm.juc.threadpool;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/***
 * 线程测试类
 */
public class ThreadTest {

    public static void main(String[] args) throws InterruptedException {
        // 使用线程的方式去执行程序
        newThread();
        // 使用线程池的方式去执行程序
        newPool();
    }

    private static void newPool() throws InterruptedException {
        final Random random = new Random();
        final List<Integer> list = new ArrayList<>();
        long start = System.currentTimeMillis();
        ExecutorService executorService = Executors.newFixedThreadPool(4);
        for (int i = 0; i < 100000; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    list.add(random.nextInt());
                }
            });
        }
        executorService.shutdown();
        executorService.awaitTermination(1, TimeUnit.DAYS);
        System.out.println("【使用线程池】时间：" + (System.currentTimeMillis() - start));
        System.out.println("【使用线程池】大小：" + list.size());
    }

    private static void newThread() throws InterruptedException {
        final Random random = new Random();
        final List<Integer> list = new ArrayList<>();
        long start = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            Thread thread = new Thread(() -> list.add(random.nextInt()));
            thread.start();
            thread.join();
        }
        System.out.println("【使用独立线程】时间：" + (System.currentTimeMillis() - start));
        System.out.println("【使用独立线程】大小：" + list.size());
    }
}